<?php

namespace app\salesman\controller;

use app\salesman\model\Salesman;

class Controller extends \app\BaseController
{
    protected $salesman = null;

    protected function initialize()
    {
        $accessToken = $this->request->header('Authorization');
        if (empty($accessToken)) {
            $this->showError('登录已过期，请重新登录。');
        }
        $salesmanInfo = cache($accessToken);
        if (empty($salesmanInfo)) {
            $this->showError('登录已过期，请重新登录');
        }

        $salesman = Salesman::where([
            'id' => $salesmanInfo['salesman_id'] ?? 0,
            'is_deleted' => DELETE_TYPE_NO,
        ])->find();


        if (empty($salesman)) {
            $this->showError('登录已过期，请重新登录！');
        }
        if ($salesman['status'] != 1) {
            $this->showError('账号被禁用');
        }

        $auth = new \app\salesman\model\Auth;
        $auth->refreshToken($salesmanInfo['refresh_token']);
        $this->salesman = $salesman;
    }

    private function showError($message)
    {
        exit(json_encode([
            'code' => 401,
            'message' => $message,
            'data' => [],
        ], JSON_UNESCAPED_UNICODE));
    }
}
